//define global variables
//2011-07-27 add var for welcome page
var welcomeLoaded = false;
var friendLoaded = false;
var neighbourLoaded = false;
var mineLoaded = false;
var mineEditLoaded = false;
var recommendLoaded = false;

//Total slide count
var slideCount;
var thisSlideSeq;
var nextSlideSeq;
            
//Friend slide count
var friendSlideCount;
var friendThisSlideSeq;
var friendNextSlideSeq;
            
//Recommend slide count
var recommendSlideCount;
var recommendThisSlideSeq;
var recommendNextSlideSeq;
            
//Tag related variables
var tagCount;
var tagId;
var tagMaxNumber;

//Random people related flags
var randomPeopleList = [];
var randomPeopleSeq = 0;

var lat; //纬度
var lon;  //经度 

$(document).ready(function(){
    //把login.js中的内容整合进来
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function getPositionSuccess(position) { 
                lat = position.coords.latitude; //纬度
                lon = position.coords.longitude;  //经度 
                $("#longitude").val(lon);
                $("#latitude").val(lat);
                $("#longitude_register").val(lon);
                $("#latitude_register").val(lat);
                $.post("get_address.php",{
                    longitude:lon,
                    latitude:lat
                },function(response){
                    var data;
                    if(response == 'fail'){
                        data = '定位失败';
                    }else
                    {
                        data = '你当前的位置：<br/>'+response;
                        loadRandom();
                    }
                    $('#locationTip').html(data);
                });
                $('#locationLoading').hide();
                $("#loginBtn").text('登录').attr("disabled",false);
            }
            ,function getPositionError(error){
                switch(error.code){
                    case error.TIMEOUT:
                        $('#locationTip').html('连接超时，请登录再尝试定位');
                        break;
                    case error.PERMISSION_DENIED:
                        $('#locationTip').html('抱歉，你已禁止定位功能，请允许系统的定位请求');
                        break;
                    case error.POSITION_UNAVAILABLE:
                        $('#locationTip').html('抱歉，我们暂时无法为您提供定位服务');
                        break;
                }
            },{
                timeout: 4000
            });
    } else {
        $('#locationTip').text('抱歉，你的浏览器不支持GeoLocation定位功能');
    }
    //卿 2011-6-10
    //POST()函数调用的语法格式如下所示:$.post(url,[data],[callback],[type])
    //url表示等待加载的数据地址，可选项[data]表示发送到服务器的数据其格式为key/value
    //可选项目[callback]参数表示加载成功时执行的回调函数
    //可选项[type]表示返回数据的格式，如html,xml,js,json,text等
    //注册验证  POST
    $('#rigisterLoading').hide();
    //验证密码前注册按钮不可用
    //$('#rigisterBtn').attr("disabled",true);
    $('#email_input').blur(function(){
        $('#rigisterLoading').show();
        $.post("register_check.php", {
            useremail: $('#email_input').val()
        }, function(response){
            $('#rigisterResult').fadeOut();
            setTimeout("finishAjax('rigisterResult', '"+escape(response)+"')", 400);
        });
        return false;
    });
    $('#rigisterBtn1').bind('vclick',function(){
        //var email = $('#email_input').val();
        var psw1 = $('#password_input').val();
        var psw2 = $('#password_confirm').val();
        if(psw1 != psw2){
            alert("输入的两次密码不一致");
            return false;
        }else{
            $.post('register.php', $('form#signup_form').serialize(), function(){
                window.location = "index.php?page=1";
            })
        }
    });
                
    $('#loginLoading').hide();
    //将覆盖原有的submit方法   李本卿  2011-6-13
    $("#login").submit
    (
        function()
        {
            login();
            return false;
        }
        );
    
    //Modified by Stan 2011/7/4
    setPage();
    
    $("#recommend_button").bind('vclick', function (){
        $.mobile.changePage('recommend.php', 'slideup');
        if(!recommendLoaded)loadRecommend(1);
        $("ul.l-list li.l-recommend-more").live('vclick', getNextRecommendSlide);
    });
                
    bind();

});
   
function login()
{
    var email = $("#email").val();
    var password = $("#password").val();
    var longitude=$('#longitude').val();
    var latitude=$('#latitude').val();
     
    $.ajax({
        type: "POST",
        url: "login.php",
        data: "email=" + email + "&password=" + password+"&longitude="+longitude+"&latitude="+latitude,
        beforeSend: function(){
            $('#loginLoading').show();
        },
        success: function(msg){
            if(escape(msg) == 'success'){
                $('#loginLoading').hide();
                // $("#confirm").html("\u767b录中"); 
                location.href = "index.php";
            }else {
                $('#loginLoading').hide();
                $("#confirm").html("\u7528户名或者密\u7801错误，请重新输入").fadeOut(4000);
            }
        }
    });
}

function finishAjax(id, response) {
    $('#rigisterLoading').hide();
    $('#'+id).html(unescape(response));
    $('#'+id).fadeIn();
    $('#'+id).fadeOut(5000);
}
//               
//2011-07-27 function to show welcome page
function showWelcome(){
    hideAll();
    showWelcomeBar();  
    
    $("#welcome_content").show();
    
    //Set timer
    loadRandom();
    //不能为3300秒
    tm = setInterval("setRandom()",3000);
}

//2011-07-27 function to hide all pages and buttons
function hideAll(){
    //Hide welcome
    $("#welcome_content").hide();
    //Hide refresh button
    
    
    //Hide neighbour
    $("#neighbour_content").hide();
    $("#slide_control").hide();
    $("#prev_button").hide();
    $("#next_button").hide();

    //Hide friend
    $("#friend_content").hide();
    
    //Hide mine
    $("#mine_content").hide();
    $("#edit_button").hide();
    $("#cancel_button").hide();
}


function showWelcomeBar(){
    $("#index_header").hide();
    $("#index_footer").hide();
    
    $("#welcome_header").show();
    $("#welcome_footer").show();
    


}

function hideWelcomeBar(){
    $("#index_header").show();
    $("#index_footer").show();
    
    $("#welcome_header").hide();
    $("#welcome_footer").hide();
    
//Delete timer
//clearInterval(tm);

}

function showMain(){
    hideAll();
    hideWelcomeBar();
    $("#next_button").show();
    $("#prev_button").show();
    $("#neighbour_content").show();
    $("#slide_control").show();

    if(!neighbourLoaded)
    {
        loadNeighbour(1);
        $("#next_button").show();
    }
    else
    {
        if(thisSlideSeq > 1)$("#prev_button").show();
    }
    $("#neighbour_content").show();
    $("#slide_control").show();
}

function showFriend(){
    hideAll();
    hideWelcomeBar();

    $("#friend_content").show();    
    if(!friendLoaded)loadFriend(1);

    $("#search_button").show();
    $("ul.l-list li.l-friend-more").bind('vclick', getNextFriendSlide);

}

function showMine(){
    hideAll();
    hideWelcomeBar();

    $("#mine_content").show();
    if(!mineLoaded)loadMine();
    $("#edit_button").show();
    //for new tweet operation in profile.php
    $("#new_tweet").live("mousedown",function (){
        $("#submit_tweet").removeClass("l-displaynone");
        $(this).val("");
    });
        
    $("#submit_tweet").live("vclick", function (){
        //Todo 评论存入数据库 并在回调函数中 执行hideComment
        $.post("tweet_update.php", {
            content:$(this).parent().prev().val()
        },function(){
            alert('状态更新成功');       
        });
    });
}
     
//2011-07-31 Stan 更新随机用户
function setRandom(){
    //Generate random number
    rnd.today=new Date();
    rnd.seed=rnd.today.getTime();
    function rnd() {
        rnd.seed = (rnd.seed*9301+49297) % 233280;
        return rnd.seed/(233280.0);
    };
    var blockId = Math.ceil(rnd()*3-1);
    {
        var image = "./images/avatar.png";
        if(randomPeopleList[randomPeopleSeq].image != null)image = randomPeopleList[randomPeopleSeq].image;
        var status_image = "./images/offline.png";
        if(randomPeopleList[randomPeopleSeq].is_online == "1") status_image = "./images/online.png";
        //        $html = $("#random_people_"+ blockId).html();
        //        $($html).find('div.l-avatar').attr('style', "background-image:url('+ randomPeopleList[randomPeopleSeq].image +')");
        //        $($html).find('div.l-status p').text(randomPeopleList[randomPeopleSeq].distance);
        //        $($html).find('div.l-status h4').text(randomPeopleList[randomPeopleSeq].nick_name);
        //
        $html = "";
        //        $html += '<div class="l-avatar l-shadowbox" style="background-image:url('+ randomPeopleList[randomPeopleSeq].image +')">';
        //        $html += '<div class="l-status">';
        //        $html += '<img src="/images/online.png"/>';
        //        $html += '<p>'+randomPeopleList[randomPeopleSeq].distance+'</p>';
        //        $html += '</div>';
        //        $html += '<h4>'+randomPeopleList[randomPeopleSeq].nick_name+'</h4>';
        //        $html += '</div>';
        $html += '<a class="ui-link">';
        $html += '<div class="l-avatar l-shadowbox" style="background-image:url('+ image +')">';
        $html += '<div class="l-status">';
        $html += '<img src="'+ status_image +'">';
        $html += '<p class="ui-li-desc">'+randomPeopleList[randomPeopleSeq].distance+'</p>';
        $html += '</div>';
        $html += '<h4 class="ui-li-heading">'+randomPeopleList[randomPeopleSeq].nick_name+'</h4>';
        $html += '</div>';
        $html += '</a>';


    }
    //    $("#welcome_content ul li:first-child div.ui-grid-b div:eq("+ blockId +") div.l-people a").html($html);
    //    alert($("#random_people_"+ blockId).html());
    $("#random_people_"+ blockId).html($html);
    randomPeopleSeq ++;
    if(randomPeopleSeq >= 23)randomPeopleSeq = 0;
}

//added 07-24 Stan 
function setPage(){
    var $_GET = new Array();
    var url = window.location.toString();
    url = url.split('?');
    if(typeof(url[1]) == 'string'){
        url = url[1].split('&');
        for(i=0;i<url.length;i++)
        {
            s = url[i].split("=");
            eval('$_GET["' + s[0] + '"]' + '="' + s[1]+'"');
        }
    }
    
    var page = $_GET["page"];
    switch(page){
        case "-1":
            showWelcome();
            break
        case "0":
            showMain() ;
            break
        case "1":
            showFriend();
            break
        case "2":
            showMine();
            break
        default:
            showMain();
    }

}

//added 07-15 Stan
function refresh(){
    //Clear content
    $("#neighbour_content div").remove();
    //Reset state variables
    neighbourLoaded = false;
    
    if(!neighbourLoaded)loadNeighbour(1);
    
    
    if(friendLoaded){
        $("#friend_content ul.l-list li.l-list-item").remove();
        friendLoaded = false;
        if(!friendLoaded)loadFriend(1);
    }
    
    if(mineLoaded){
        $("#mine_content ul li").remove();
        mineLoaded = false;
        if(!mineLoaded)loadMine();
    }
    
    bind();

    
}

//newly added 06-15 stan
function getNextSlide(){

    
    //Get slide count
    slideCount = $('div.l-slide:first').attr("data-slide-count");
    if(thisSlideSeq < Number($('div.l-slide:last').attr('data-slide-seq'))){
        nextSlideSeq = Number(thisSlideSeq) + 1;
        slideLeft();
    }
    else if(!thisSlideSeq){
        thisSlideSeq = $("div.l-slide:last").attr('data-slide-seq');
        nextSlideSeq = Number(thisSlideSeq) + 1;
        if(nextSlideSeq <= slideCount)loadNeighbour(nextSlideSeq);
    }
    
    //Display buttons
    $("#prev_button").show();
    if(nextSlideSeq >= slideCount)$("#next_button").hide();
}
            
function getPrevSlide(){
    //Implemented by Stan 2011-6-27
    nextSlideSeq = Number(thisSlideSeq) - 1;
    if(nextSlideSeq >= 1)slideRight();
    
    //Display buttons
    $("#next_button").show();
    if(thisSlideSeq <= 1)$("#prev_button").hide();
}

//Added by Stan 2011-6-27
function slideLeft(){

    //Step 1 before transition, hide new slide and its pager                 
    //Hide this slide pager before this page appears
    $('.l-slide:last').next().hide();

    //Set this slide to the rightmost
    $('.l-slide:last').css('left','210%');
    
    
    //Step 2 hide last pager and slide last slide to the leftmost                
    //Hide last slide pager
    $('.l-slide:last').prev().hide();

    //Set old slide to the leftmost and hide it
    $('.l-slide:last').prev().prev().animate({
        'left':'-110%',
        'opacity':'100'
    }, 'normal',function (){
        $(this).css('display', 'none');
    });
    
    
    //Step 3 slide new slide to the center and display the pager
    $('.l-slide:last').delay(450).animate({
        'left':'0'
    }, 'normal',function (){
        $(this).css('display', 'block')
        $(this).next().show();
    });
    
    thisSlideSeq++;
    bindSwipe();
}

//Added by Stan 2011-6-27
function slideRight(){

    //Step 1 hide new pager and slide new slide to the rightmost                
    //Hide new slide pager
    $('.l-slide:last').next().hide();
    
    $('.l-slide:last').animate({
        'left':'210%',
        'opacity':'100'
    }, 'normal',function (){
        $(this).css('display', 'none');
    });
    

    //Slide old slide to the center
    $('.l-slide:last').delay(450).show().prev().prev().animate({
        'left':'0'
    }, 'normal',function (){
        $(this).css('display','block');
        $(this).next().show();
    });
    
    //    
    //    //Step 3 slide new slide to the center and display the pager
    //    $('.l-slide:last').delay(450).animate({
    //        'left':'0'
    //    }, 'normal',function (){
    //        $(this).next().show();
    //    });

    thisSlideSeq --;
    bindSwipe();
}

function bindSwipe(){
    $("div.l-slide:last").bind('swipeleft',getNextSlide);
    $("div.l-slide:last").bind('swiperight',getPrevSlide);
}
            
//Function to deal with friend loading
function getNextFriendSlide(){
    //    alert("loaded");
    friendSlideCount = $('div#friend_content ul.l-list li:first-child').attr("data-slide-count");
    
    friendNextSlideSeq = Number(friendThisSlideSeq) +1;
    if(friendThisSlideSeq < friendSlideCount ){
        loadFriend(friendNextSlideSeq);
        if(friendNextSlideSeq == friendSlideCount)$("ul.l-list li.l-friend-more").hide();
    }
}

//Function to deal with recommend loading
function getNextRecommendSlide(){
    recommendSlideCount = $('div#recommend_content ul.l-list li:first-child').attr("data-slide-count");
    
    recommendNextSlideSeq = Number(recommendThisSlideSeq) +1;
    if(recommendThisSlideSeq < recommendSlideCount ){
        loadRecommend(recommendNextSlideSeq);
        if(recommendNextSlideSeq == recommendSlideCount)$("ul.l-list li.l-recommend-more").hide();
    }
}

//Private functions
function addTag()
{
    $(this).show();
    $('.l-taglist input').each(function (){
        //enhancePage();
        tagId = $(this).attr("data-tag-id");
        if ( tagId == tagCount) {
            $(this).parent().show();
                        
            tagCount++;
            if(tagCount >= tagMaxNumber){
                tagCount--;
                displayMessage("max tag size");
                hideMessage(1000);
                            
            }
            return false;
        }
    });
    $(this).addClass('l-display');
    $(this).addClass('l-button-inactive');
}
            
function checkNumber(){
    //alert($(this).attr('value'));
    var warning = $(this).siblings('label.l-warning');
    warning.addClass('l-hidden');

    var number = Number($(this).attr('value'));
    var max = Number($(this).attr('max'));
    var min = Number($(this).attr('min'));
    if((number > max)||(number < min))warning.removeClass('l-hidden');
}
            
function setImage(fatherElem)
{
    $(fatherElem).find(".l-avatar").each(function (){
        if($(this).attr("data-img") != null)
            $(this).css("background-image","url("+$(this).attr("data-img")+")");
    });
}

            
//A serial of load function
function loadWelcome(){
}


function loadNeighbour(slide_seq){
    displayMessage();
    if (typeof slide_seq == 'undifined')slide_seq = 1;
    url = "neighbour.php?slide_seq=" + slide_seq;
    //var spacing = $('body').width();
    $.get(url, function(data){
        hideMessage();
        $("#neighbour_content").append(data);
        setImage(".l-people");
        
        //Modified by Stan 2011-6-27
        slideLeft();
    });
    neighbourLoaded = true;                
}
            
function loadFriend(slide_seq){
    displayMessage();
    if (typeof slide_seq == 'undifined')slide_seq = 1;
    url = "friend.php?slide_seq=" + slide_seq;
    $.get(url, function(data){
        hideMessage();
        $("div#friend_content ul.l-list li.l-friend-more").before(data);
        $("div#friend_content ul.l-list").listview('refresh');
        setImage(".l-list");
    });
    friendLoaded = true;
    
    friendThisSlideSeq = slide_seq;
}

function loadRecommend(slide_seq){
    displayMessage();
    if (typeof slide_seq == 'undifined')slide_seq = 1;
    url = "recommend_people.php?slide_seq=" + slide_seq;
    $.get(url, function(data){
        hideMessage();
        $("ul.l-list li.l-recommend-more").before(data);
        $("ul.l-list").listview('refresh');
        setImage(".l-list");
    });
    recommendLoaded = true;
    
    recommendThisSlideSeq = slide_seq;
}

//2011-07-31 Stan 读取随机用户函数
function loadRandom(){
    $.getJSON('random.php', {
        longitude: lon, 
        latitude:lat
    }, function (data){
        randomPeopleList = [];
        randomPeopleList.length = 0;
        $.each(data, function (i, item) {
            randomPeopleList.push(item);
        });
    //        alert(data[0].user_id);
    //        $.extend(true, randomPeopleList, data);
        
    //        alert(randomPeopleList[randomPeopleSeq].user_id);
    
    });
        
//    })
    
}
            
function loadMine(){
    displayMessage();
    $("#tweet_list").load("profile.php ul#tweet_list li", function(){
        hideMessage();
        $("ul#tweet_list").listview('refresh');
    //        setImage(".l-profile-view li");
    });
    $("#information_list").load("profile.php ul#information_list li", function(){
        hideMessage();
        $("ul#information_list").listview('refresh');
    //        setImage(".l-profile-view li");
    });
    mineLoaded = true;                
}  
            
function loadMineEdit(){
    $.mobile.changePage('profile_edit.php', 'slideup');
    $('div').live('pageshow',function(){
        //Slide 1px up to adjust view
        $.mobile.silentScroll (1);
                    
        //Bind number checker onto keypress event
        $('input.l-number').keyup(checkNumber);
                    
        tagCount = $('#new_tag').attr('data-tag-count');
        tagMaxNumber = $('#new_tag').attr('data-tag-max-number');

        $('.l-taglist div').each(function (){
            var tagId = Number($(this).children('input').attr('data-tag-id'));
            if(tagId >= tagCount)$(this).hide();
        });
        // late bind click event 
        $('.l-taglist div:last-child input').next('a').bind('tap',addTag);
    //$('#new_tag + a').bind('tap',addTag);
                    
    // $('a#edit_confirm').bind('vclick', postForm);
    //$('a#edit_confirm').bind('tap', postForm);
    });
}

//common utility functions

function bind (){
    $("#main_tab").bind('vclick',showMain);
    $("#friend_tab").bind('vclick',showFriend);
    $("#mine_tab").bind('vclick',showMine);
    
    $("#refresh_button").bind("vclick", refresh)
    $("#edit_button").bind('vclick',loadMineEdit);
    $("#next_button").bind('vclick',getNextSlide);
    $('#prev_button').bind('vclick',getPrevSlide);

}
function displayMessage(message){
    $("<div class='l-message ui-loader ui-body-a ui-corner-all'>" + "<span class='ui-icon ui-icon-loading spin'></span>" + "<h1>" + (message?message:"loading") + "</h1>" + "</div>")
    .css({
        "display": "block", 
        "opacity": 0.96, 
        "top": $.support.scrollTop && $(window).scrollTop() + $(window).height() / 2 || 100
    })
    .appendTo( $.mobile.pageContainer );
}
            
function hideMessage(time){
    $(".l-message").fadeOut( time?time:400, function(){
        $(this).remove();
    });
}
